#!/usr/bin/python -d
#-*- coding:utf-8 -*-

import getpass
import socket
from optparse import OptionParser
from sys import exit
import sys
import formatter

import logging
logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s %(filename)s:%(lineno)d - %(levelname)s: %(message)s")


def test_connection(target_host, port):
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.settimeout(0.5)
   result = -1
   #connect_ex no da excepciones, devuelve el valor 
   result = s.connect_ex((target_host, port))
   logging.debug("Socket.Connect returns code %s" %result)
   s.close()
   return result==0


def send_command(command, host, port):
   res   = 1
   tries = 3
   while ( tries > 0 ):
      try:
         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         s.connect((host, port))
         logging.debug("Sent from %s" %( repr(command)))
         returned = s.send(command)
         #logging.debug("The call send returns %s (bytes sent?)" %repr(returned))
         res = 0
         break
      except Exception as e:
         logging.error( "Error sending command %s to %s:%s \nReason: %s"
                        %(command, host, port, str(e)))
      finally:
         s.close()
         tries -= 1
   if( tries==0 and res!=0):
      logging.error("After 3 tries the request can't be sent %s:%s" %(host,port))
   return res

def main():
   
   HOST = 'f0'
   PORT = 30000
   
   loged_user = getpass.getuser()
   
   # comprobamos si hay conectividad con el equipo
   if( test_connection(HOST, PORT)==True):
      logging.debug("Hay conexión con %s:%s" %(HOST, PORT))
      result = send_command(loged_user, HOST, PORT)
      sys.exit(result)
   else:
      logging.info("Imposible conectar con %s por el puerto %s"
                   %(HOST, PORT))
      sys.exit(1)


if __name__ == "__main__":
    
    main()
